package robot

import (
	"context"
	"sale-admin/config/mysql"
	"sale-admin/internal/app/web/service"
	"sale-admin/internal/models"
	"strings"
	"time"

	"192.168.1.75/go-pkg/errorx"
	"github.com/samber/lo"
	"gorm.io/gorm"
)

type RobotClick struct {
}

type GoodsClickType struct {
	CurrentHour string `json:"current_hour"`
	GoodsID     string `json:"goods_id"`
	RobotName   string `json:"robot_name"`
	ClickNum    int    `json:"click_num"`
}

// 获取今日点击数
func (r RobotClick) GetRobotGoodsClick(ctx context.Context, db *gorm.DB, salesID string, start_time, end_time string) (res []GoodsClickType, err error) {

	// 商品点击数表
	tx := db.Model(&models.MaGoodsClick{})
	if strings.TrimSpace(salesID) != "" {
		tx.Where("sales_id = ?", strings.TrimSpace(salesID))
	}

	tx.Where("start_time between ? and ?", start_time, end_time)
	tx.Select(
		"date_format(start_time, '%H') as curr_hour",
		"goods_id",
		"robot_name",
		"sum(click_num) as click_num",
	)
	tx.Group("goods_id")
	tx.Order("goods_id desc")
	rowsAffected := tx.Find(&res).RowsAffected
	if rowsAffected <= 0 {
		return []GoodsClickType{}, errorx.New("无数据", -1)
	}
	return
}

type UpGoodsClickData struct {
	SalesID   string `json:"SalesID"`
	RobotName string `json:"RobotName"`
	ClickData []struct {
		ClickNum  int64  `json:"ClickNum"`
		EndTime   int64  `json:"EndTime"`
		GoodsID   string `json:"GoodsID"`
		StartTime int64  `json:"StartTime"`
	} `json:"ClickData"`
}

// 上报点击量
func (r RobotClick) UpGoodsClick(ctx context.Context, db *gorm.DB, upGoodsClickData UpGoodsClickData) (err error) {
	RobotInfo, robotExist := RobotService{}.CheckRobotExist(ctx, db, upGoodsClickData.SalesID, "")
	if !robotExist {
		err = errorx.New("找不到机器人", -1)
		return
	}
	var BatchInsert []models.MaGoodsClick
	var affectedDays []string

	for _, v := range upGoodsClickData.ClickData {
		var ClickInfoCount int64
		mysql.NewDB().Model(&models.MaGoodsClick{}).
			Where("sales_id = ? and goods_id = ?", upGoodsClickData.SalesID, v.GoodsID).
			Where("start_time = ? and end_time = ?", time.Unix(v.StartTime, 0), time.Unix(v.EndTime, 0)).
			Count(&ClickInfoCount)
		if ClickInfoCount == 0 {
			var InsertData models.MaGoodsClick
			InsertData.ID = RobotInfo.MerchantID
			InsertData.MerchantID = RobotInfo.MerchantID
			InsertData.SalesID = upGoodsClickData.SalesID
			InsertData.RobotName = upGoodsClickData.RobotName
			InsertData.AddTime = time.Now()
			InsertData.ClickNum = v.ClickNum
			InsertData.StartTime = time.Unix(v.StartTime, 0)
			InsertData.EndTime = time.Unix(v.EndTime, 0)
			InsertData.NewStartTime = v.StartTime
			InsertData.NewEndTime = v.EndTime
			InsertData.GoodsID = v.GoodsID
			InsertData.CreatedDate = time.Unix(v.StartTime, 0)
			BatchInsert = append(BatchInsert, InsertData)
		} else {
			mysql.NewDB().Model(&models.MaGoodsClick{}).
				Where("sales_id = ? and goods_id = ?", upGoodsClickData.SalesID, v.GoodsID).
				Where("start_time = ? and end_time = ?", time.Unix(v.StartTime, 0), time.Unix(v.EndTime, 0)).
				Updates(&map[string]interface{}{
					"click_num": v.ClickNum,
				})
		}
		day := time.Unix(v.StartTime, 0).Format("2006-01-02")
		if !lo.Contains(affectedDays, day) {
			affectedDays = append(affectedDays, day)
		}
		// 商品日报表更新点击量
		service.GoodsDailyReport{}.UpdateGoodsClick(ctx, db, RobotInfo.RobotName, v.GoodsID, day)
	}
	if len(BatchInsert) > 0 {
		mysql.NewDB().Model(&models.MaGoodsClick{}).Create(&BatchInsert)
	}
	if len(affectedDays) > 0 {
		// 更新机器运营日报点击量
		for _, v := range affectedDays {
			service.RobotDailyReport{}.UpdateGoodsClick(ctx, db, RobotInfo.RobotName, v)
		}
	}

	return
}
